<template>
  <div ref="wrapper">
    <slot></slot>
  </div>
</template>

<script>
import betterScroll from "better-scroll";
export default {
  props: {
    probeType: {
      type: Number,
      default() {
        return 1;
      },
    },
    click: {
      type: Boolean,
      default() {
        return true;
      },
    },
    direction: {
      type: String,
      default() {
        return "horizontal";
      },
    },
    listenScroll: {
      type: Boolean,
      default() {
        return false;
      },
    },
    pullup: {
      type: Boolean,
      default() {
        return false;
      },
    },
    pulldown: {
      type: Boolean,
      default() {
        return false;
      },
    },
    data: {
      type: Array,
      default: null,
    },
    beforeScroll: {
      type: Boolean,
      default: false,
    },
  },
  mounted() {
    setTimeout(() => {
      this._initScroll();
    }, 20);
  },
  methods: {
    _initScroll() {
      this.scroll = new betterScroll(this.$refs.wrapper, {
        probeType: this.probeType,
        click: this.click,
        eventPassthrough:
          this.direction === "vertical" ? "vertical" : "horizontal",
      });

      // 是否派发滚动事件
      if (this.listenScroll) {
        this.scroll.on("scroll", (pos) => {
          this.$emit("scroll", pos);
        });
      }

      // 是否派发滚动到底部事件
      if (this.pullup) {
        this.scroll.on("scrollEnd", () => {
          if (this.scroll.y <= this.scroll.maxScrollY + 50) {
            this.$emit("scrollToEnd");
          }
        });
      }

      // 是否下拉刷新
      if (this.pulldown) {
        this.scroll.on("touchEnd", (pos) => {
          if (pos.y > 50) {
            this.$emit("pulldown");
          }
        });
      }

      // 是否派发滚动开始的事件
      if (this.beforeScroll) {
        this.scroll.on("beforeScrollStart", () => {
          this.$emit("beforeScroll");
        });
      }
    },
    refresh() {
      console.log('refresh');
      this.scroll && this.scroll.refresh();
    },
  },
  watch: {
    data: function () {
      setTimeout(() => {
        this.refresh();
      }, 20);
    },
  },
};
</script>

<style>
</style>